#include<func.h>
//编写火车站买票，两个子线程卖票，确保没有卖负票
typedef struct{
    int tickets;
    pthread_mutex_t mutex;
}data_t;

void* sale_windows1(void*p)//卖票窗口1
{
    int i;
    data_t* d=(data_t*)p;
    while(1)
    {
        pthread_mutex_lock(&d->mutex);//判断之前就加锁，否则出现负票
        if(d->tickets>0)
        {
            printf("windows1 stsrt sale %d\n",d->tickets);
            d->tickets--;
            pthread_mutex_unlock(&d->mutex);
            printf("windows1 finish sale %d\n",d->tickets);
        }
        else{
            pthread_mutex_unlock(&d->mutex);
            break;
        }
    }
}

void* sale_windows2(void*p)//卖票窗口2
{
    int i;
    data_t* d=(data_t*)p;
    while(1)
    {
        pthread_mutex_lock(&d->mutex);//判断之前就加锁，否则出现负票
        if(d->tickets>0)
        {
            printf("windows1 stsrt sale %d\n",d->tickets);
            d->tickets--;
            pthread_mutex_unlock(&d->mutex);
            printf("windows1 finish sale %d\n",d->tickets);
        }
        else{
            pthread_mutex_unlock(&d->mutex);
            break;
        }
    } 
}

int main()
{
    data_t d;
    d.tickets=20;
    pthread_t pthid[2];
    int ret=pthread_mutex_init(&d.mutex,NULL);//初始化锁
    THREAD_ERR_CHECK(ret,"pthread_mutex_init");
    ret=pthread_create(&pthid[0],NULL,sale_windows1,(void*)&d);//创建线程1
    THREAD_ERR_CHECK(ret,"pthread_create1");
    ret=pthread_create(&pthid[1],NULL,sale_windows2,(void*)&d);//创建线程2
    THREAD_ERR_CHECK(ret,"pthread_create2");
    ret=pthread_join(pthid[0],NULL);//等待线程1
    THREAD_ERR_CHECK(ret,"pthread_join");
    ret=pthread_join(pthid[1],NULL);//等待线程1
    THREAD_ERR_CHECK(ret,"pthread_join");
    printf("main thread tickets %d\n",d.tickets);
    ret=pthread_mutex_destroy(&d.mutex);//销毁锁
    THREAD_ERR_CHECK(ret,"pthread_mutex_destroy")
    return 0;
}